package com.fengyunhe.common.utils;

import com.fengyunhe.utils.http.HttpClients;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.ArrayUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * 功能：下载图片工具
 * 作者： yangyan
 * 时间： 2014/9/11 .
 */
public class ImageCatchUtil {


    public static boolean catchImg(String url, File distFile) {
        HttpClient client = HttpClients.instance();
        URL urlObject = null;
        try {
            urlObject = new URL(url);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        if (url == null || "".equals(url)) {
            return false;
        }
        HttpGet httpGet = new HttpGet(url);

        httpGet.setHeader(
                "Host",
                urlObject.getHost());
        httpGet.setHeader("Connection", "keep-alive");
        httpGet.setHeader("Cache-Control", "no-cache");
        httpGet.setHeader("Pragma", "no-cache");
        httpGet.setHeader(
                "User-Agent",
                "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11");
        httpGet.setHeader("Accept",
                "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
        httpGet.setHeader("Accept-Encoding", "gzip,deflate,sdch");
        httpGet.setHeader("Accept-Language", "zh-CN,zh;q=0.8");
        httpGet.setHeader("Accept-Charset", "GBK,utf-8;q=0.7,*;q=0.3");
        httpGet.setHeader("Cache-Control", "no-cache");
        httpGet.setHeader("Pragma", "no-cache");
        HttpResponse response = null;
        try {
            response = client.execute(httpGet);
        } catch (IOException e) {
            e.printStackTrace();
        }
        String contentType = response.getHeaders("Content-Type")[0]
                .getValue();
        String[] picTypes = {"image/jpeg", "image/gif", "image/bmp",
                "image/x-png", "image/png"};
        boolean isPic = ArrayUtils.contains(picTypes, contentType);
        if (!isPic) {
            return false;
        }
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            InputStream is = null;
            try {
                is = entity.getContent();
                FileUtils.copyInputStreamToFile(is, distFile);
                return true;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return false;
    }
}
